const Router = require("koa-router")
const ResBody = require("../struct/ResBody")
const { Op } = require('sequelize');
const moment = require("moment")

const { Order, OrderGoods, Customer, Cate, Goods, GoodsAttrConfig, GoodsAttrValue, GoodsAttr, Building, User, Room, Floor } = require("../model")

const { OrderController, CustomerController } = require("../controller")
const router = new Router()
const utils = require("../utils/index.js")

// 列表model
router.get("/index", async ctx => {
  const store_id = ctx.header.storeid;
  const query = ctx.request.query;
  const { paging, id, order_no, customer_id, company_name, status, startTime, endTime } = query;
  console.log('order/index--status:-%s-%s==', JSON.stringify(status), typeof (status));
  console.log('order/index--query:-%s==', JSON.stringify(ctx.request.query));

  const pagings = {
    limit: 50,
    page: 1
  };
  if (paging) {
    pagings.limit = paging.limit;
    pagings.page = (paging.page - 1) * pagings.limit;
  }
  const params = {};

  if (status) {
    params.status = {
      [Op.in]: status.split(",")
    }
  }
  if (id) {
    params.id = id
  }
  if (order_no) {
    params.order_no = {
      [Op.like]: `%${order_no}%`
    }
  }
  if (customer_id) {
    params.customer_id = customer_id
  }
  if (company_name) {
    params.company_name = {
      [Op.like]: `%${company_name}%`
    }
  }

  if (startTime && endTime) {
    params.create_time = {
      [Op.between]: [startTime, endTime]
    }
  }

  // let list = [], count = 0;
  // const res = await Order.findAll({
  const { rows: list, count } = await Order.findAndCountAll({
    where: { store_id, ...params },
    // ...pagings
    limit: pagings.limit || 50, // 每页多少条
    offset: pagings.limit * (pagings.page - 1) || 0, // 跳过多少条
    order: [["id", "DESC"]]
  });

  // console.log('Order/index--res==%s==', JSON.stringify(res));
  console.log('Order--index--list==%s==', JSON.stringify(list));
  ctx.body = new ResBody({ data: { list, count } })
})
// 列表 sql
router.get("/index2", async ctx => {
  const store_id = ctx.header.storeid;
  try {
    const rsp = await OrderController.getOrderList({ store_id })
    console.log("order/index2--rsp: %s==", JSON.stringify(rsp));
  }
  catch (err) {
    console.log('order/index2--err:%s==', JSON.stringify(err));
    const errorData = utils.errorBody(err)
    console.log('order/index2--errorData:%s==', JSON.stringify(errorData));
    return ctx.body = new ResBody({ data: errorData })
    // return ctx.body = new ResBody({ data: { code: 0, msg: '失败' } })
  }
})
// 订单详情
router.get("/detail", async ctx => {
  // console.log('goods_index--%s===', JSON.stringify(ctx));
  const store_id = ctx.header.storeid;
  const { id } = ctx.request.query
  console.log("order/detail--id:%s==", id);

  const data = await OrderController.getOrderDetail({ id });
  console.log('order/detail==%s==', data);
  if (!data) {
    return ctx.body = new ResBody({ data: '未找到该数据', code: 500, msg: '未找到该数据' })
  }
  ctx.body = new ResBody({ data })
})
// 添加订单；
router.post("/add", async ctx => {
  const { role } = ctx.state.user
  const { storeid: store_id, storeno: store_no } = ctx.header;
  console.log("order/detail--%s--%s==", store_id, store_no);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  // order_type订单类型：1: 采购入库，2: 销售出库，3: 同价调拨， 4: 其他入库，5: 采购退货，6: 报溢单，7: 报损单，8: 其他出库
  const {
    customer_id,
    company_name,
    order_type,
    coupon_price = 0,
    freight_price = 0,
    total_num,
    total_price,
    discount = 1,
    status = 0,
    pay_status = '',
    pay_time = '',
    is_delete = 0,
    remarks,
    goods_list
  } = ctx.request.body;
  utils.checkParams({ customer_id, company_name, order_type, total_num, total_price, goods_list });
  try {
    const rsp = await OrderController.createOrder({ ...ctx.request.body, store_id, store_no });
    console.log('order/add--data:%s==', JSON.stringify(rsp));
    return ctx.body = new ResBody({ ...rsp })
  }
  catch (err) {
    console.log('order/add--err:%s==', JSON.stringify(err));
    const errorData = utils.errorBody(err)
    console.log('order/add--errorData:%s==', JSON.stringify(errorData));
    return ctx.body = new ResBody({ code: 500, data: errorData })
    // return ctx.body = new ResBody({ data: { code: 0, msg: '失败' } })
  }
})
// 更新订单状态；
router.post("/updataStatus", async ctx => {
  const { role } = ctx.state.user
  const { storeid: store_id, storeno: store_no } = ctx.header;
  if (role !== "superAdmin") {
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }

  const {
    id,
    status
  } = ctx.request.body;
  utils.checkParams({ id, status });
  try {
    // 更新订单状态操作
    const rsp = await OrderController.updataStatus({ ...ctx.request.body, store_id });
    console.log('order/updataStatus--data:%s==', JSON.stringify(rsp));

    // CustomerController.updateCustomerConfig(ctx.request.body);

    return ctx.body = new ResBody({ ...rsp })
  }
  catch (err) {
    console.log('order/updataStatus--err:%s==', JSON.stringify(err));
    const errorData = utils.errorBody(err)
    console.log('order/updataStatus--errorData:%s==', JSON.stringify(errorData));
    return ctx.body = new ResBody({ data: errorData })
    // return ctx.body = new ResBody({ data: { code: 0, msg: '失败' } })
  }
})
// 添加商品；
router.post("/update", async ctx => {
  const { role } = ctx.state.user
  const store_id = ctx.header.storeid;
  console.log('store_id==%s==', store_id);
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_name, full_goods_name, cat_id, attr = '', stock = '0', sales = '0', unit_name, unit_name2 = '', unit_convert = 1, unit_convert2 = 1, weight = 0, desc = '', sort = 500, is_hot = 0, is_recommend = 0, status = 1, is_delete = 0, slider_image = '', content } = ctx.request.body
  utils.checkParams({ goods_name, full_goods_name, unit_name, cat_id, stock, unit_name2, unit_convert, unit_convert2 })

  const goods = CustomerController.updateGoods({ ...ctx.request.body, store_id })
  // const goods = await Goods.findOrCreate({ where: { goods_name, full_goods_name, store_id }, defaults: { goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, sort, store_id, is_hot, is_recommend, status, is_delete, slider_image, content } })
  console.log('goods--typeof(goods):%s==', typeof (goods), JSON.stringify(goods));
  ctx.body = new ResBody({ data: goods })
})

// 修改商品规格 
router.post("/updateAttrValue", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id, attr_list } = ctx.request.body
  const attrResult = CustomerController.bulkCreateGoodsAttr({ ...ctx.request.body }, id, store_id)
  console.log('attrResult--%s==', attrResult);

  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
})

// 修改商品规格(废弃)
router.post("/updateAttrValue2", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_id, attr_list } = ctx.request.body
  const list = attr_list.map(d => {
    d.goods_id = goods_id;
    return d;
  })
  console.log('updateAttrValue--goods_id: %s--attr_list: %s==', goods_id, JSON.stringify(list));
  GoodsAttrValue.bulkCreate(list, { updateOnDuplicate: ["price", "retail_price", "cost_price", "stock", "weight", "code", "sort"] })
    .then(res => {
      console.log('updateAttrValue--res: %s==', JSON.stringify(res));
    })
    .catch(err => {
      console.log('updateAttrValue--err: %s==', JSON.stringify(err));
    })

  ctx.body = new ResBody({ data: '', code: 200, msg: '操作成功' })
  return;

  utils.checkParams({ goods_id })

  const findData = await GoodsAttrConfig.findOrCreate({ where: { goods_id, store_id }, defaults: { goods_id, store_id, config } })
  console.log('findData--%s==', JSON.stringify(findData));
  if (!findData[1]) {
    const res = await GoodsAttrConfig.update(
      { config }, {
      where: { goods_id, store_id }
    })
    console.log('GoodsAttrConfig.update--res--%s==', res);
    return ctx.body = new ResBody({ data: res, code: 200, msg: '操作成功' })
  }
  ctx.body = new ResBody({ data: findData, code: 200, msg: '操作成功' })
})

// 添加商品规格配置 attr_config；
router.post("/updateAttrConfig", async ctx => {
  const store_id = ctx.header.storeid;
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { id: goods_id, attr_list } = ctx.request.body
  utils.checkParams({ goods_id })

  const findData = await GoodsAttrConfig.findOrCreate({ where: { goods_id }, defaults: { goods_id, config: JSON.stringify(attr_list) } })
  console.log('findData--%s==', JSON.stringify(findData));
  if (!findData[1]) {
    const res = await GoodsAttrConfig.update(
      { config: JSON.stringify(attr_list) },
      {
        where: { goods_id }
      })
    console.log('GoodsAttrConfig.update--res--%s==', res);
    return ctx.body = new ResBody({ data: res, code: 200, msg: '操作成功' })
  }
  // if (findData) {
  //   // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
  //   return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  // }
  // const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
  ctx.body = new ResBody({ data: findData, code: 200, msg: '操作成功' })
})


// 添加商品规格；
router.post("/addAttr", async ctx => {
  console.log('addAttr--%s--%s==', JSON.stringify(ctx), JSON.stringify(ctx.state.user));
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return ctx.body = new ResBody({ success: false, code: 403, msg: '拒绝访问API' })
  }
  const { goods_id, store_id, attr_name, attr_values, status, is_delete = 0 } = ctx.query
  utils.checkParams({ goods_id, store_id, attr_name, attr_values })

  const findGoods = await Goods.findOne({ where: { goods_name, full_goods_name, store_id } })
  console.log('findGoods--%s==', findGoods);
  if (findGoods) {
    // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
    return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  }
  const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
  ctx.body = new ResBody({ data: goods })
})

router.get("/getManageBuildings", async ctx => {
  const { role, userId } = ctx.state.user
  const user = await User.findById(userId)
  let buildings = []
  switch (user.role) {
    case "superAdmin":
      buildings = await Building.findAll()
      break
    case "admin":
      buildings = await user.getBuildings()
      break
    default:
      buildings = []
      break
  }
  ctx.body = new ResBody({ data: { buildings, role } })
})

router.get("/getBuildingInfo", async ctx => {
  const { buildingId } = ctx.request.query
  const building = await Building.findOne({ where: { id: buildingId } })
  const result = building.toJSON()
  result.floorCount = await Floor.count({ where: { buildingId } })
  result.roomCount = await Room.count({ where: { buildingId } })
  result.studentCount = (
    await BuildingController.getStudents(buildingId)
  ).length
  ctx.body = new ResBody({ data: result })
})

router.post("/addBuildingWithRoom", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { name, floorCount, roomCount } = ctx.request.body
  utils.checkParams({ name, floorCount, roomCount })
  const building = await Building.createBuilding({ name })
  // 为宿舍楼添加楼层
  for (let i = 1; i <= floorCount; i++) {
    const floor = await Floor.createFloor({ layer: i, buildingId: building.id })
    await Building.addFloor(building.id, floor)
    // 为楼层添加房间
    for (let j = 1; j <= roomCount; j++) {
      await Room.createRoom({
        number: i * 100 + j,
        floorId: floor.id,
        buildingId: building.id
      })
    }
  }
  ctx.body = new ResBody({ data: building })
})

router.del("/delBuilding", async ctx => {
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    throw new Error("403-拒绝访问API")
  }
  const { id } = ctx.request.query
  const result = await BuildingController.delBuilding(id)
  ctx.body = new ResBody({ data: result })
})

router.get("/getAdminTableData", async ctx => {
  const { buildingId } = ctx.request.query
  utils.checkParams({ buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const admins = await building.getAdmins()
  ctx.body = new ResBody({ data: { admins, total: admins.length } })
})

router.get("/getCleanerTableData", async ctx => {
  const { buildingId } = ctx.request.query
  utils.checkParams({ buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const cleaners = await building.getCleaners()
  ctx.body = new ResBody({ data: { cleaners, total: cleaners.length } })
})

router.post("/addAdminToBuilding", async ctx => {
  const { adminAccount, buildingId } = ctx.request.body
  const admin = await User.findOne({
    where: { account: adminAccount, role: "admin" }
  })
  if (!admin) {
    throw new Error("找不到该用户")
  }
  const result = await Building.addAdmin(buildingId, admin.id)
  if (!result) {
    throw new Error("403-目标管理员已为当前宿舍楼的管理员，添加失败")
  }
  ctx.body = new ResBody({ data: { result } })
})

router.del("/removeBuildingAdmin", async ctx => {
  const { adminId, buildingId } = ctx.request.query
  utils.checkParams({ adminId, buildingId })
  const building = await Building.findOne({ where: { id: buildingId } })
  const admin = await User.findOne({ where: { id: adminId } })
  const result = await building.removeAdmin(admin)
  ctx.body = new ResBody({ data: { effectRow: result } })
})

module.exports = router.routes()
